package cn.bitkit.assist.code.creator;

import cn.bitkit.assist.code.BaseCreator;
import cn.bitkit.assist.code.vo.FieldVO;
import cn.bitkit.base.util.PathUtil;
import cn.bitkit.tools.file.TextHelper;

import java.util.stream.Collectors;

public class VueCreator extends BaseCreator {

	@Override
	public void create() {
		createFile("vue-index.tpl", "index");
		createFile("vue-add.tpl", "add");
		createFile("vue-update.tpl", "update");
	}

	private void createFile(String tplFile, String fileName){
		final String template = getTemplate(tplFile);
		TextHelper builder = TextHelper.loadString(template);
		builder.setValue("entityName", entityVO.getEntityName());
		builder.setValue("entityVar", entityVO.getEntityVar());
		builder.setValue("modelName", projectVO.getModuleName());
		boolean query = "index".equals(fileName);
		builder.setValue("fieldInput", getFieldInput(query));
		builder.setValue("fieldForm", getFieldForm(query));
		builder.setValue("fieldRule", getFieldRule());
		builder.setValue("fieldTable", getFieldTable());
		String text = builder.getText();
		String filePath = PathUtil.asPath(projectVO.getAbsoluteWebFolder(), "/views/", projectVO.getModuleName(), entityVO.getEntityVar());
		writeText(text, filePath + fileName +".vue");
	}

	private String getFieldInput(boolean query){
		final String template = getTemplate("vue-input.tpl");
		return entityVO.getFieldList().stream()
				.filter(FieldVO::getInput)
				.map(e -> {
					TextHelper builder = TextHelper.loadString(template);
					builder.setValue("formName", query ? "state.queryForm" : "dataForm");
					builder.setValue("valid", query ? "" : " prop=\""+e.getField()+"\"");
					builder.setValue("fieldName", e.getField());
					builder.setValue("fieldLabel", e.getName());
					return builder.getText();
				}).collect(Collectors.joining("\n"));
	}

	private String getFieldForm(boolean query){
		return entityVO.getFieldList().stream()
				.filter(FieldVO::getInput)
				.map(e -> "\t"+(query?"\t":"")+e.getField()+": ''")
				.collect(Collectors.joining(",\n"));
	}

	private String getFieldRule(){
		return entityVO.getFieldList().stream()
				.filter(FieldVO::getInput)
				.map(e -> "\t"+e.getField()+": [{ validator: validator, require: true, type: 'AN', trigger: 'blur' }]")
				.collect(Collectors.joining(",\n"));
	}

	private String getFieldTable(){
		return entityVO.getFieldList().stream()
				.filter(FieldVO::getInput)
				.map(e -> "\t\t\t<el-table-column prop=\""+e.getField()+"\" label=\""+e.getName()+"\" header-align=\"center\" align=\"center\"></el-table-column>")
				.collect(Collectors.joining("\n"));
	}

}
